package praktikumid.w10.p4;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

public class Polygon extends Shape {
	private List<Point> points = new ArrayList<Point>();
	
	private boolean isLastPointFinished = true;
	
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		for (int i = 1; i < points.size(); i++) {
			g.drawLine(points.get(i).x, points.get(i).y,
					points.get(i - 1).x,
					points.get(i - 1).y);
		}
		if (isFinished) {
			g.drawLine(points.get(0).x, points.get(0).y, 
					getLastPoint().x,
					getLastPoint().y);
		}
		
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		points.add(e.getPoint());
		if (e.getClickCount() > 1) {
			isFinished = true;
		}
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		if (isLastPointFinished) {
			if (points.size() == 0) {
				// start point
				points.add(e.getPoint());
			}
			points.add(e.getPoint());
			isLastPointFinished = false;
		} else {
			getLastPoint().setLocation(e.getPoint());
		}
	}
	
	@Override
	public void mouseReleased(MouseEvent e) {
		isLastPointFinished = true;
	}
	
	public Point getLastPoint() {
		if (points.size() == 0) return null;
		return points.get(points.size() - 1);
	}
	
	@Override
	public int getDistance(Point p) {
		int minDistance = Integer.MAX_VALUE;
		for (Point p2 : points) {
			int d = (int) p.distance(p2);
			if (d < minDistance) {
				minDistance = d;
			}
		}
		return minDistance;
	}
	
	public void move(int dx, int dy) {
		for (Point p : points) {
			p.x += dx;
			p.y += dy;
		}
	};
}
